<?php
class Response {
    protected $model = array();
    protected $headers = array();
    protected $redirect = false;
    protected $responseCode = 200;
    
    public function __get($key) {
        return isset($this->model[$key]) ? $this->model[$key] : NULL;
    }
    public function __set($key, $value) {
        $this->setModel($key, $value);
    }
    public function setModel($key, $value) {
        $this->model[$key] = $value;
    }
    public function getModel() {
        return $this->model;
    }
    public function setHeader($value) {
        $this->canSendHeaders(true);
        $this->headers[] = $value;
        return $this;
    }
    public function clearHeaders() {
        $this->headers = array();
    }
    public function setRouter($router) {
        if (isset($this->model['router']))
            throw new Exception('Response::model::router can not be assign!');
        $this->model['router'] = $router;
    }
    public function getRouter() {
        return $this->model['router'];
    }
    public function setRedirect($url, $code = 302) {
        $this->setHeader("Location: $url")
             ->setHttpResponseCode($code);
        $this->redirect = true;
        return $this;
    }
    public function hasRedirect() {
    	return $this->redirect;
    }
    public function setHttpResponseCode($code) {
        $this->responseCode = $code;
        return $this;
    }
    public function sendHeaders() {
        foreach ($this->headers as $header) {
            header($header);
        }
        header("HTTP/1.1 {$this->responseCode}");
        return $this;
    }
    public function canSendHeaders($throw = false) {
        $sent = headers_sent($file, $line);
        if ($sent && $throw) {
            throw new Exception("Cannot send headers; headers already sent in $file , line $line");
        }
        return !$sent;
    }
    public function setFor404()
    {
        $this->setHeader("Cache-Control: Private");
        $this->setHeader("Status: 404 Not Found");  
        $this->setHttpResponseCode('404 Not Found');
    }

    public function exitJump($url, $code=302)
    {
        if (301 == $code)
        {
            header("HTTP/1.1 301 Moved Permanently"); 
        }
        header('Location: '.$url);
        exit;
    }
}
?>
